package com.vaha.presentation.rest;

import com.cyber.application.controller.AuthingTokenController;
import com.cyber.domain.constant.HttpResultCode;
import com.cyber.domain.entity.DataResponse;
import com.cyber.domain.entity.IdRequest;
import com.cyber.domain.entity.PagingData;
import com.cyber.domain.entity.Response;
import com.vaha.application.service.CommissionService;
import com.vaha.domain.entity.Commission;
import com.vaha.domain.request.CommissionRequest;
import com.vaha.domain.request.CreateCommissionRequest;
import com.vaha.domain.request.UpdateCommissionRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

@RestController
@RequiredArgsConstructor
public class CommissionRest extends AuthingTokenController{

	private final CommissionService commissionService;

	@GetMapping("/commission/search")
	public Response searchCommission(@Valid CommissionRequest request) {
		DataResponse<PagingData<Commission>> response = new DataResponse<>();
        Commission  commission = request.toEvent(getTenantCode());
		PagingData<Commission> commissionPage = commissionService.selectPage(commission);
		response.setData(commissionPage);
		return response;
	}


	@GetMapping("/commission")
	public Response selectOneCommission(@Valid IdRequest idRequest) {
		DataResponse<Commission> response = new DataResponse<>();

		Commission commission = new Commission();
		commission.setId(idRequest.getId());
        commission.setTenantCode(getTenantCode());
		commission = commissionService.selectOne(commission);

		response.setData(commission);
		return response;
	}

	@PostMapping("/commission")
	public Response saveCommission(@RequestBody @Valid CreateCommissionRequest request) {
	    Commission  commission = request.toEvent(getSessionId(),getTenantCode());

		int result = commissionService.save(commission);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}

	@PutMapping("/commission")
	public Response updateCommission(@RequestBody @Valid UpdateCommissionRequest request) {
	    Commission  commission = request.toEvent(getSessionId(),getTenantCode());
		int result = commissionService.updateById(commission);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}

	@DeleteMapping("/commission")
	public Response deleteCommission(@Valid IdRequest idRequest) {
		Commission commission = new Commission();
		commission.setId(idRequest.getId());

		commission.setTenantCode(getTenantCode());
		commission.setUpdator(getSessionId());
        commission.setUpdateTime(new Date());

		int result = commissionService.deleteById(commission);
		if (result < 1) {
			return Response.fail(HttpResultCode.SERVER_ERROR);
		}
		return Response.success();
	}
}
